package com.starry.push.netty.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.starry.push.netty.domain.LogPushTask;
import com.starry.push.netty.domain.LogWsConnect;
import com.starry.push.netty.service.LogPushTaskService;
import com.starry.push.netty.service.LogWsConnectService;
import com.starry.push.netty.vo.ClientText;
import com.starry.push.netty.vo.ClientTextVo;
import com.starry.push.netty.vo.ResponseResult;
import com.starry.push.netty.vo.WsResponse;
import com.starry.push.netty.websocket.WebSocketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author WuChao
 * @version 1.0
 * @date 2020/11/3 16:22
 */
@RestController
@RequestMapping("/push")
@Slf4j
@AllArgsConstructor
public class PushController {

    private LogWsConnectService logWsConnectService;
    private LogPushTaskService logPushTaskService;

    @PostMapping("/common")
    public ResponseEntity common(@RequestBody ClientTextVo clientText) {

        if (StringUtils.isBlank(clientText.getChannelId())) {
            if (StringUtils.isBlank(clientText.getUniqueIdentification())) {
                return ResponseEntity.ok(ResponseResult.error("推送id和唯一标识不能同时为空"));
            }
        }
        if (StringUtils.isNotBlank(clientText.getUniqueIdentification())) {
            List<LogWsConnect> connects = logWsConnectService.list(new QueryWrapper<LogWsConnect>()
                    .eq(LogWsConnect.COL_UNIQUE_IDENTIFICATION, clientText.getUniqueIdentification())
                    .eq(LogWsConnect.COL_STATUS, 1)
            );
            if (CollectionUtils.isNotEmpty(connects)) {
                connects.forEach(logWsConnect -> {
                    String idStr = IdWorker.getIdStr();
                    WsResponse response = WsResponse.success(idStr, "正常", clientText.getMsg());
                    Channel channel = WebSocketHandler.onlineGroup.get(logWsConnect.getChannelId());
                    if (channel != null) {
                        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
                        logPushTaskService.save(
                                LogPushTask.builder().channelId(channel.id().asLongText())
                                        .pushId(idStr)
                                        .status(1)
                                        .createTime(LocalDateTime.now())
                                        .uniqueIdentification(clientText.getUniqueIdentification())
                                        .content(JSONObject.toJSONString(clientText))
                                        .build());
                    }


                });
            }else {
                return ResponseEntity.ok(ResponseResult.error("无有效链接"));
            }
        }

        if (StringUtils.isNotBlank(clientText.getChannelId())) {
            List<LogWsConnect> connects = logWsConnectService.list(new QueryWrapper<LogWsConnect>()
                    .eq(LogWsConnect.COL_CHANNEL_ID, clientText.getChannelId())
                    .eq(LogWsConnect.COL_STATUS, 1)
            );
            if (CollectionUtils.isNotEmpty(connects)) {
                connects.forEach(logWsConnect -> {
                    String idStr = IdWorker.getIdStr();
                    WsResponse response = WsResponse.success(idStr, "正常", clientText);
                    Channel channel = WebSocketHandler.onlineGroup.get(logWsConnect.getChannelId());
                    if (channel != null) {
                        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response))).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
                        logPushTaskService.save(
                        LogPushTask.builder().channelId(channel.id().asLongText())
                                .pushId(idStr)
                                .status(1)
                                .createTime(LocalDateTime.now())
                                .uniqueIdentification(clientText.getUniqueIdentification())
                                .build());
                    }
                });
            }else {
                return ResponseEntity.ok(ResponseResult.error("无有效链接"));
            }
        }

        return ResponseEntity.ok(ResponseResult.success());
    }
}
